<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '请选择省市区'
  }
})

const emit = defineEmits(['update:modelValue'])

// 地区数据（简化版，实际项目中应该从API获取）
const regionData = reactive({
  provinces: [
    { code: '110000', name: '北京市' },
    { code: '120000', name: '天津市' },
    { code: '130000', name: '河北省' },
    { code: '140000', name: '山西省' },
    { code: '150000', name: '内蒙古自治区' },
    { code: '210000', name: '辽宁省' },
    { code: '220000', name: '吉林省' },
    { code: '230000', name: '黑龙江省' },
    { code: '310000', name: '上海市' },
    { code: '320000', name: '江苏省' },
    { code: '330000', name: '浙江省' },
    { code: '340000', name: '安徽省' },
    { code: '350000', name: '福建省' },
    { code: '360000', name: '江西省' },
    { code: '370000', name: '山东省' },
    { code: '410000', name: '河南省' },
    { code: '420000', name: '湖北省' },
    { code: '430000', name: '湖南省' },
    { code: '440000', name: '广东省' },
    { code: '450000', name: '广西壮族自治区' },
    { code: '460000', name: '海南省' },
    { code: '500000', name: '重庆市' },
    { code: '510000', name: '四川省' },
    { code: '520000', name: '贵州省' },
    { code: '530000', name: '云南省' },
    { code: '540000', name: '西藏自治区' },
    { code: '610000', name: '陕西省' },
    { code: '620000', name: '甘肃省' },
    { code: '630000', name: '青海省' },
    { code: '640000', name: '宁夏回族自治区' },
    { code: '650000', name: '新疆维吾尔自治区' }
  ],
  cities: {
    '110000': [{ code: '110100', name: '北京市' }],
    '120000': [{ code: '120100', name: '天津市' }],
    '130000': [
      { code: '130100', name: '石家庄市' },
      { code: '130200', name: '唐山市' },
      { code: '130300', name: '秦皇岛市' },
      { code: '130400', name: '邯郸市' },
      { code: '130500', name: '邢台市' },
      { code: '130600', name: '保定市' },
      { code: '130700', name: '张家口市' },
      { code: '130800', name: '承德市' },
      { code: '130900', name: '沧州市' },
      { code: '131000', name: '廊坊市' },
      { code: '131100', name: '衡水市' }
    ],
    '440000': [
      { code: '440100', name: '广州市' },
      { code: '440200', name: '韶关市' },
      { code: '440300', name: '深圳市' },
      { code: '440400', name: '珠海市' },
      { code: '440500', name: '汕头市' },
      { code: '440600', name: '佛山市' },
      { code: '440700', name: '江门市' },
      { code: '440800', name: '湛江市' },
      { code: '440900', name: '茂名市' },
      { code: '441200', name: '肇庆市' },
      { code: '441300', name: '惠州市' },
      { code: '441400', name: '梅州市' },
      { code: '441500', name: '汕尾市' },
      { code: '441600', name: '河源市' },
      { code: '441700', name: '阳江市' },
      { code: '441800', name: '清远市' },
      { code: '441900', name: '东莞市' },
      { code: '442000', name: '中山市' },
      { code: '445100', name: '潮州市' },
      { code: '445200', name: '揭阳市' },
      { code: '445300', name: '云浮市' }
    ]
    // 其他省份的城市数据可以根据需要添加
  },
  districts: {
    '440100': [
      { code: '440103', name: '荔湾区' },
      { code: '440104', name: '越秀区' },
      { code: '440105', name: '海珠区' },
      { code: '440106', name: '天河区' },
      { code: '440111', name: '白云区' },
      { code: '440112', name: '黄埔区' },
      { code: '440113', name: '番禺区' },
      { code: '440114', name: '花都区' },
      { code: '440115', name: '南沙区' },
      { code: '440117', name: '从化区' },
      { code: '440118', name: '增城区' }
    ],
    '440300': [
      { code: '440303', name: '罗湖区' },
      { code: '440304', name: '福田区' },
      { code: '440305', name: '南山区' },
      { code: '440306', name: '宝安区' },
      { code: '440307', name: '龙岗区' },
      { code: '440308', name: '盐田区' },
      { code: '440309', name: '龙华区' },
      { code: '440310', name: '坪山区' },
      { code: '440311', name: '光明区' }
    ]
    // 其他城市的区县数据可以根据需要添加
  }
})

const selectedRegion = reactive({
  province: '',
  city: '',
  district: ''
})

const showDropdown = ref(false)
const currentLevel = ref('province') // province, city, district
const displayText = ref('')

// 当前显示的选项列表
const currentOptions = computed(() => {
  switch (currentLevel.value) {
    case 'province':
      return regionData.provinces
    case 'city':
      return regionData.cities[selectedRegion.province] || []
    case 'district':
      return regionData.districts[selectedRegion.city] || []
    default:
      return []
  }
})

// 选择省份
const selectProvince = (province) => {
  selectedRegion.province = province.code
  selectedRegion.city = ''
  selectedRegion.district = ''
  
  if (regionData.cities[province.code] && regionData.cities[province.code].length > 0) {
    currentLevel.value = 'city'
  } else {
    // 直辖市等没有下级城市的情况
    updateDisplayText()
    showDropdown.value = false
    emitValue()
  }
}

// 选择城市
const selectCity = (city) => {
  selectedRegion.city = city.code
  selectedRegion.district = ''
  
  if (regionData.districts[city.code] && regionData.districts[city.code].length > 0) {
    currentLevel.value = 'district'
  } else {
    // 没有下级区县的情况
    updateDisplayText()
    showDropdown.value = false
    emitValue()
  }
}

// 选择区县
const selectDistrict = (district) => {
  selectedRegion.district = district.code
  updateDisplayText()
  showDropdown.value = false
  emitValue()
}

// 更新显示文本
const updateDisplayText = () => {
  const parts = []
  
  if (selectedRegion.province) {
    const province = regionData.provinces.find(p => p.code === selectedRegion.province)
    if (province) parts.push(province.name)
  }
  
  if (selectedRegion.city) {
    const cities = regionData.cities[selectedRegion.province] || []
    const city = cities.find(c => c.code === selectedRegion.city)
    if (city) parts.push(city.name)
  }
  
  if (selectedRegion.district) {
    const districts = regionData.districts[selectedRegion.city] || []
    const district = districts.find(d => d.code === selectedRegion.district)
    if (district) parts.push(district.name)
  }
  
  displayText.value = parts.join(' ')
}

// 发送值给父组件
const emitValue = () => {
  emit('update:modelValue', displayText.value)
}

// 打开下拉框
const openDropdown = () => {
  showDropdown.value = true
  currentLevel.value = 'province'
}

// 关闭下拉框
const closeDropdown = () => {
  showDropdown.value = false
}

// 返回上一级
const goBack = () => {
  if (currentLevel.value === 'city') {
    currentLevel.value = 'province'
  } else if (currentLevel.value === 'district') {
    currentLevel.value = 'city'
  }
}

// 监听外部点击关闭下拉框
onMounted(() => {
  document.addEventListener('click', (e) => {
    if (!e.target.closest('.region-select')) {
      closeDropdown()
    }
  })
})

// 初始化显示值
watch(() => props.modelValue, (newValue) => {
  if (newValue && newValue !== displayText.value) {
    displayText.value = newValue
  }
}, { immediate: true })
</script>

<template>
  <div class="region-select">
    <div class="select-input" @click="openDropdown">
      <input 
        type="text" 
        :value="displayText" 
        :placeholder="placeholder"
        readonly
      />
      <span class="arrow" :class="{ 'arrow-up': showDropdown }">▼</span>
    </div>
    
    <div v-if="showDropdown" class="dropdown">
      <div class="dropdown-header" v-if="currentLevel !== 'province'">
        <button @click="goBack" class="back-btn">← 返回</button>
        <span class="level-title">
          {{ currentLevel === 'city' ? '选择城市' : '选择区县' }}
        </span>
      </div>
      
      <div class="options-list">
        <div 
          v-for="option in currentOptions" 
          :key="option.code"
          class="option-item"
          @click="currentLevel === 'province' ? selectProvince(option) : 
                  currentLevel === 'city' ? selectCity(option) : 
                  selectDistrict(option)"
        >
          {{ option.name }}
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.region-select {
  position: relative;
  width: 100%;
}

.select-input {
  position: relative;
  cursor: pointer;
  
  input {
    width: 100%;
    padding: 12px 40px 12px 16px;
    border: 1px solid #e1e5e9;
    border-radius: 8px;
    font-size: 14px;
    cursor: pointer;
    background: #fff;
    box-sizing: border-box;
    
    &:focus {
      outline: none;
      border-color: #1dbf73;
    }
    
    &::placeholder {
      color: #999;
    }
  }
  
  .arrow {
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%);
    color: #999;
    font-size: 12px;
    transition: transform 0.2s;
    
    &.arrow-up {
      transform: translateY(-50%) rotate(180deg);
    }
  }
}

.dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: #fff;
  border: 1px solid #e1e5e9;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  max-height: 300px;
  overflow: hidden;
}

.dropdown-header {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  background: #f8f9fa;
  
  .back-btn {
    background: none;
    border: none;
    color: #1dbf73;
    cursor: pointer;
    font-size: 14px;
    margin-right: 12px;
    
    &:hover {
      color: #17a863;
    }
  }
  
  .level-title {
    font-size: 14px;
    color: #191e28;
    font-weight: 500;
  }
}

.options-list {
  max-height: 240px;
  overflow-y: auto;
}

.option-item {
  padding: 12px 16px;
  cursor: pointer;
  font-size: 14px;
  color: #191e28;
  border-bottom: 1px solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
  
  &:hover {
    background: #f8f9fa;
    color: #1dbf73;
  }
}
</style>